import { Injectable, ConflictException, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Users } from '@modules/users/entities/user.entity';
import { RegisterDto } from './dto/register.dto';
import { decrypt } from '@utils/crypto.util';
import { ApiResponse } from '@common/interfaces/api-response.interface'
import { LoginDto } from './dto/login.dto';
import { CaptchaService } from './captcha.service';

@Injectable()
export class AuthService {
  private readonly encryptionKey = 'my-secret-key'; // 加密密钥
  constructor(
    @InjectRepository(Users)
    private usersRepository: Repository<Users>,
    private captchaService: CaptchaService, // 注入验证码服务
  ) { }

  // 检查邮箱是否已存在
  async checkIfEmailExists(email: string): Promise<void> {
    const existingUser = await this.usersRepository.findOne({ where: { email } });
    if (existingUser) {
      throw new ConflictException('邮箱已存在');
    }
  }

  // 检查用户名是否已存在
  async checkIfUsernameExists(username: string): Promise<void> {
    const existingUser = await this.usersRepository.findOne({ where: { username } });
    if (existingUser) {
      throw new ConflictException('用户名已存在');
    }
  }

  // 注册用户
  async register(registerDto: RegisterDto): Promise<ApiResponse<Users>> {
    try {
      // 检查邮箱和用户名是否已存在
      await Promise.all([
        this.checkIfEmailExists(registerDto.email),
        this.checkIfUsernameExists(registerDto.username),
      ]);

      // 加密密码
      // const encryptedPwd = encrypt(registerDto.password, this.encryptionKey); // 加密邮箱

      // 创建用户
      const newUser = this.usersRepository.create(registerDto);

      // 保存用户
      const savedUser = await this.usersRepository.save(newUser);
      return {
        code: 200,
        message: '用户注册成功',
        data: savedUser,
      };
    } catch (error) {
      return {
        code: 500,
        message: '用户注册失败',
        error: error.message,
      };
    }
  }

  // 登录用户
  async login(loginDto: LoginDto,sessionId: string): Promise<ApiResponse<any>> {
    // 验证验证码
    const isCaptchaValid = this.captchaService.validateCaptcha(sessionId, loginDto.captcha);
    
    if (!isCaptchaValid) {
      throw new UnauthorizedException('验证码错误');
    }

    // 验证用户名和密码
    const user = await this.usersRepository.findOne({ where: { username: loginDto.username } });
    if (user && decrypt(loginDto.password, this.encryptionKey) === user.password) {
      // 登录成功，返回用户信息或 Token
      const { password, ...result } = user;
      return {
        code:200,
        data:result,
        message:'登录成功'
      };
    }
    throw new UnauthorizedException('用户名或密码错误');
  }
} 